package com.minzheng.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.minzheng.blog.dao.CategoryDao;
import com.minzheng.blog.dao.MovieDao;
import com.minzheng.blog.dto.MovieDTO;
import com.minzheng.blog.entity.Category;
import com.minzheng.blog.entity.Movie;
import com.minzheng.blog.service.MovieService;
import com.minzheng.blog.util.BeanCopyUtils;
import com.minzheng.blog.util.PageUtils;
import com.minzheng.blog.vo.ConditionVO;
import com.minzheng.blog.vo.MovieVO;
import com.minzheng.blog.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;


/**
 * 电影服务
 *
 * @author silencezheng
 * @date 2022/08/10
 */
@Service
@Slf4j
public class MovieServiceImpl extends ServiceImpl<MovieDao, Movie> implements MovieService {
	@Autowired
	private MovieDao movieDao;
	@Autowired
	private CategoryDao categoryDao;

	@Override
	public PageResult<MovieDTO> listMovies(ConditionVO condition) {
		// 查询总量
		Integer count = movieDao.getCount(condition);
		if (count <= 0) {
			return new PageResult<>();
		}
		// 查询后台电影列表
		List<MovieDTO> movieDTOList = movieDao.listMovies(PageUtils.getLimitCurrent(), PageUtils.getSize(), condition);
		return new PageResult<>(movieDTOList, count);
	}

	@Override
	public void deleteMovies(List<Integer> movieIdList) {
		movieDao.deleteBatchIds(movieIdList);
	}

	@Override
	@Transactional
	public void saveOrUpdateMovie(MovieVO movieVO) {
		// 保存电影分类
		Category category = saveMovieCategory(movieVO);
		// 保存或修改电影
		Movie movie = BeanCopyUtils.copyObject(movieVO, Movie.class);
		if (Objects.nonNull(category)) {
			movie.setCategoryId(category.getId());
		}
		this.saveOrUpdate(movie);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Movie listMovieById(Integer id) {
		movieDao.updateViewsCount(id);
		return movieDao.selectById(id);
	}

	@Override
	public void toRate(Integer id, Integer userRate) {
		movieDao.toRate(id,userRate);
	}

	/**
	 * 保存电影分类
	 *
	 * @param movieVO 电影信息
	 * @return {@link Category} 电影分类
	 */
	private Category saveMovieCategory(MovieVO movieVO) {
		// 判断分类是否存在
		Category category = categoryDao.selectOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName, movieVO.getCategoryName()));
		if (Objects.isNull(category)) {
			category = Category.builder().categoryName(movieVO.getCategoryName()).build();
			category.setType("1");
			categoryDao.insert(category);
		}
		return category;
	}
}
